import RNFS, { DownloadFileOptions, DownloadResult } from 'react-native-fs';
import customAwait from '../customAwait';

export default async (
  options: DownloadFileOptions
): Promise<{ jobId: number; promise: Promise<DownloadResult> }> => {
  const realFilePath = options.toFile;
  const filePathArray = realFilePath.split('/');
  const fileName = filePathArray.pop();
  const fakePath = [...filePathArray, 'temp'].join('/');
  const fakeFilePath = `${fakePath}/${fileName}`;

  await RNFS.mkdir(fakePath);

  const ret = RNFS.downloadFile({ ...options, toFile: fakeFilePath });

  const [error, res] = await customAwait(ret.promise);

  // 下载成功
  if (res && res.statusCode === 200) {
    const isExist = await RNFS.exists(realFilePath);
    if (isExist) {
      await RNFS.unlink(realFilePath);
    }
    await RNFS.moveFile(fakeFilePath, realFilePath);
  }

  return ret;
};
